<template>
  <div>
    <el-container>
      <SidebarMenu
        :default-active="activeMenu"
        @goToRoleManagement="goToRoleManagement"
        @goToMenuManagement="goToMenuManagement"
        @goToPermissionControl="goToPermissionControl"
        @goToSystemSetting="goToSystemSetting"
        @goToLogManagement="goToLogManagement"
        @goToFileManagement="goToFileManagement"
        @goToArticleManagement="goToArticleManagement"
        @goToUserInfoManagement="goToUserInfoManagement"
      />

      <el-container>
        <el-header>
          <Navbar title="文件管理" :avatar="currentAvatar" />

        </el-header>

        <el-main>
          <!-- 查询表单 -->
          <el-card class="query-card" shadow="never">
            <el-form :inline="true" :model="queryForm">
              <el-form-item label="文件名">
                <el-input v-model="queryForm.fileName" placeholder="请输入文件名" />
              </el-form-item>
              <el-form-item label="文件类型">
                <el-select v-model="queryForm.fileType" placeholder="请选择文件类型" clearable>
                  <el-option label="图片" value="image" />
                  <el-option label="文档" value="document" />
                  <el-option label="视频" value="video" />
                  <el-option label="音频" value="audio" />
                  <el-option label="压缩包" value="archive" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
              <el-form-item label="上传者">
                <el-input v-model="queryForm.uploader" placeholder="请输入上传者姓名" />
              </el-form-item>
              <el-form-item label="上传时间">
                <el-date-picker
                  v-model="queryForm.uploadTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchFiles">查询</el-button>
                <el-button @click="resetQueryForm">重置</el-button>
                <el-button type="success" @click="showUploadDialog">上传文件</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 统计信息 -->
          <el-row :gutter="20" class="statistics-row">
            <el-col :span="6">
              <el-card class="statistics-card">
                <div class="statistics-item">
                  <div class="statistics-number">{{ statistics.totalFiles }}</div>
                  <div class="statistics-label">总文件数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="statistics-card">
                <div class="statistics-item">
                  <div class="statistics-number">{{ statistics.totalSize }}</div>
                  <div class="statistics-label">总存储空间</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="statistics-card">
                <div class="statistics-item">
                  <div class="statistics-number">{{ statistics.todayUploads }}</div>
                  <div class="statistics-label">今日上传</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="statistics-card">
                <div class="statistics-item">
                  <div class="statistics-number">{{ statistics.availableSpace }}</div>
                  <div class="statistics-label">可用空间</div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 文件表格 -->
          <el-card class="file-table-card">
            <template #header>
              <div class="card-header">
                <span>文件列表</span>
                <div class="header-actions">
                  <el-button type="warning" size="small" @click="batchDownload">批量下载</el-button>
                  <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
                </div>
              </div>
            </template>

            <el-table :data="files" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="文件信息" min-width="300">
                <template #default="scope">
                  <div class="file-info">
                    <div class="file-icon">
                      <i :class="getFileIcon(scope.row.fileType)"></i>
                    </div>
                    <div class="file-details">
                      <div class="file-name">{{ scope.row.fileName }}</div>
                      <div class="file-meta">
                        <span>{{ formatFileSize(scope.row.fileSize) }}</span>
                        <span>{{ scope.row.fileType.toUpperCase() }}</span>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="uploader" label="上传者" width="120" />
              <el-table-column prop="uploadTime" label="上传时间" width="160">
                <template #default="scope">
                  {{ formatDateTime(scope.row.uploadTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="downloadCount" label="下载次数" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusLabel(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button type="text" size="small" @click="previewFile(scope.row)">预览</el-button>
                  <el-button type="text" size="small" @click="downloadFile(scope.row)">下载</el-button>
                  <el-button type="text" size="small" @click="shareFile(scope.row)">分享</el-button>
                  <el-button type="text" size="small" @click="deleteFile(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination

                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-main>
      </el-container>
    </el-container>

    <!-- 文件上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px">
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="beforeUpload"
        :on-success="onUploadSuccess"
        :on-error="onUploadError"
        :file-list="uploadFileList"
        multiple
        drag
        class="upload-area"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持jpg/png/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/txt/zip/rar格式，单个文件不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload">开始上传</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="文件预览" width="80%" top="5vh">
      <div class="file-preview">
        <div v-if="previewFileType === 'image'" class="image-preview">
          <img :src="previewFileUrl" alt="预览图片" />
        </div>
        <div v-else-if="previewFileType === 'document'" class="document-preview">
          <iframe :src="previewFileUrl" width="100%" height="600px"></iframe>
        </div>
        <div v-else class="file-info-preview">
          <div class="preview-header">
            <h3>{{ selectedFile.fileName }}</h3>
            <div class="preview-meta">
              <span>文件大小：{{ formatFileSize(selectedFile.fileSize) }}</span>
              <span>文件类型：{{ selectedFile.fileType.toUpperCase() }}</span>
              <span>上传时间：{{ formatDateTime(selectedFile.uploadTime) }}</span>
              <span>下载次数：{{ selectedFile.downloadCount }}</span>
            </div>
          </div>
          <div class="preview-actions">
            <el-button type="primary" @click="downloadFile(selectedFile)">下载文件</el-button>
            <el-button type="success" @click="shareFile(selectedFile)">分享文件</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 文件分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="文件分享" width="500px">
      <div class="share-content">
        <div class="share-info">
          <h4>{{ selectedFile.fileName }}</h4>
          <p>文件大小：{{ formatFileSize(selectedFile.fileSize) }}</p>
        </div>
        <el-form :model="shareForm" label-width="100px">
          <el-form-item label="分享链接">
            <el-input v-model="shareForm.shareUrl" readonly>
              <template #append>
                <el-button @click="copyShareUrl">复制</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="有效期">
            <el-select v-model="shareForm.expireTime" placeholder="请选择有效期">
              <el-option label="1天" value="1" />
              <el-option label="7天" value="7" />
              <el-option label="30天" value="30" />
              <el-option label="永久" value="-1" />
            </el-select>
          </el-form-item>
          <el-form-item label="访问密码">
            <el-input v-model="shareForm.password" placeholder="可选，留空则不设置密码" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="generateShareLink">生成分享链接</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import SidebarMenu from './SidebarMenu.vue';
import Navbar from './CommonNavbar.vue'

const router = useRouter();
const activeMenu = ref('4-2'); // 文件管理菜单项
const loading = ref(false);
const uploadDialogVisible = ref(false);
const previewDialogVisible = ref(false);
const shareDialogVisible = ref(false);
const selectedFile = ref({});
const selectedRows = ref([]);
const uploadRef = ref();
const uploadFileList = ref([]);

// 查询表单
const queryForm = ref({
  fileName: '',
  fileType: '',
  uploader: '',
  uploadTime: []
});

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 统计信息
const statistics = ref({
  totalFiles: 1256,
  totalSize: '2.5GB',
  todayUploads: 23,
  availableSpace: '47.5GB'
});

// 上传相关
const uploadUrl = '/api/file/upload';
const uploadHeaders = {
  'Authorization': 'Bearer ' + localStorage.getItem('token')
};
const uploadData = {
  category: 'general'
};

// 分享表单
const shareForm = ref({
  shareUrl: '',
  expireTime: '7',
  password: ''
});

// 预览相关
const previewFileType = ref('');
const previewFileUrl = ref('');

// 文件数据
const files = ref([
  {
    id: 1,
    fileName: '产品设计图.jpg',
    fileType: 'image',
    fileSize: 2048576,
    uploader: '张三',
    uploadTime: '2024-01-15 10:30:00',
    downloadCount: 15,
    status: 'active',
    fileUrl: 'https://example.com/files/product-design.jpg'
  },
  {
    id: 2,
    fileName: '项目计划书.docx',
    fileType: 'document',
    fileSize: 512000,
    uploader: '李四',
    uploadTime: '2024-01-15 09:15:00',
    downloadCount: 8,
    status: 'active',
    fileUrl: 'https://example.com/files/project-plan.docx'
  },
  {
    id: 3,
    fileName: '演示视频.mp4',
    fileType: 'video',
    fileSize: 15728640,
    uploader: '王五',
    uploadTime: '2024-01-14 16:45:00',
    downloadCount: 32,
    status: 'active',
    fileUrl: 'https://example.com/files/demo-video.mp4'
  },
  {
    id: 4,
    fileName: '数据报表.xlsx',
    fileType: 'document',
    fileSize: 1024000,
    uploader: '赵六',
    uploadTime: '2024-01-14 14:20:00',
    downloadCount: 12,
    status: 'deleted',
    fileUrl: 'https://example.com/files/data-report.xlsx'
  }
]);

// 导航方法
const goToRoleManagement = () => {
  router.push('/RoleManagement');
};

const goToMenuManagement = () => {
  router.push('/MenuManagement');
};

const goToPermissionControl = () => {
  router.push('/PermissionControl');
};

const goToSystemSetting = () => {
  router.push('/system');
};

const goToLogManagement = () => {
  router.push('/LogManagement');
};

const goToFileManagement = () => {
  router.push('/FileManagement');
};

const goToArticleManagement = () => {
  router.push('/ArticleManagement');
};

const goToUserInfoManagement = () => {
  router.push('/UserInfoManagement');
};

// 查询方法
const searchFiles = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    console.log('查询条件:', queryForm.value);
    loading.value = false;
    ElMessage.success('查询完成');
  }, 1000);
};

const resetQueryForm = () => {
  queryForm.value = {
    fileName: '',
    fileType: '',
    uploader: '',
    uploadTime: []
  };
};

// 显示上传对话框
const showUploadDialog = () => {
  uploadDialogVisible.value = true;
  uploadFileList.value = [];
};

// 上传前验证
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf',
    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'text/plain', 'application/zip', 'application/x-rar-compressed'].includes(file.type);

  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isValidType) {
    ElMessage.error('不支持的文件类型！');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB！');
    return false;
  }
  return true;
};

// 上传成功
const onUploadSuccess = (response, file, fileList) => {
  ElMessage.success('文件上传成功');
  uploadFileList.value = fileList;
};

// 上传失败
const onUploadError = (error, file, fileList) => {
  ElMessage.error('文件上传失败');
};

// 提交上传
const submitUpload = () => {
  uploadRef.value.submit();
  uploadDialogVisible.value = false;
  searchFiles();
};

// 预览文件
const previewFile = (file) => {
  selectedFile.value = file;
  previewFileType.value = file.fileType;
  previewFileUrl.value = file.fileUrl;
  previewDialogVisible.value = true;
};

// 下载文件
const downloadFile = (file) => {
  // 模拟下载
  ElMessage.success(`开始下载文件：${file.fileName}`);
};

// 分享文件
const shareFile = (file) => {
  selectedFile.value = file;
  shareForm.value.shareUrl = `https://example.com/share/${file.id}`;
  shareDialogVisible.value = true;
};

// 生成分享链接
const generateShareLink = () => {
  ElMessage.success('分享链接生成成功');
  shareDialogVisible.value = false;
};

// 复制分享链接
const copyShareUrl = () => {
  navigator.clipboard.writeText(shareForm.value.shareUrl).then(() => {
    ElMessage.success('链接已复制到剪贴板');
  });
};

// 删除文件
const deleteFile = (file) => {
  ElMessageBox.confirm(`确定要删除文件"${file.fileName}"吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    files.value = files.value.filter(f => f.id !== file.id);
    ElMessage.success('删除成功');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 批量操作
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

const batchDownload = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要下载的文件');
    return;
  }
  ElMessage.success(`开始下载${selectedRows.value.length}个文件`);
};

const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的文件');
    return;
  }
  ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}个文件吗？此操作不可恢复！`, '批量删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    const ids = selectedRows.value.map(file => file.id);
    files.value = files.value.filter(file => !ids.includes(file.id));
    ElMessage.success('批量删除成功');
  });
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  searchFiles();
};

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  searchFiles();
};

// 格式化方法
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString('zh-CN');
};

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const getFileIcon = (fileType) => {
  const iconMap = {
    'image': 'el-icon-picture',
    'document': 'el-icon-document',
    'video': 'el-icon-video-camera',
    'audio': 'el-icon-headset',
    'archive': 'el-icon-folder',
    'other': 'el-icon-document'
  };
  return iconMap[fileType] || 'el-icon-document';
};

const getStatusType = (status) => {
  const typeMap = {
    'active': 'success',
    'deleted': 'danger',
    'processing': 'warning'
  };
  return typeMap[status] || 'info';
};

const getStatusLabel = (status) => {
  const labelMap = {
    'active': '正常',
    'deleted': '已删除',
    'processing': '处理中'
  };
  return labelMap[status] || status;
};

// 组件挂载时加载数据
onMounted(() => {
  searchFiles();
});
</script>

<style scoped>
.query-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(80, 120, 200, 0.08);
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(80, 120, 200, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}

.statistics-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(80, 120, 200, 0.12);
}

.statistics-item {
  text-align: center;
  padding: 20px 0;
}

.statistics-number {
  font-size: 28px;
  font-weight: bold;
  color: #4f46e5;
  margin-bottom: 8px;
}

.statistics-label {
  font-size: 14px;
  color: #666;
}

.file-table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(80, 120, 200, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: bold;
  color: #4f46e5;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-icon {
  width: 40px;
  height: 40px;
  background: #f0f2f5;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #666;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.file-meta {
  font-size: 12px;
  color: #666;
  display: flex;
  gap: 12px;
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(80, 120, 200, 0.08);
  background: #fff;
}

.el-table th {
  background: #e0e7ff !important;
  color: #4f46e5;
  font-weight: 600;
  font-size: 15px;
}

.el-table tr {
  transition: background 0.2s;
}

.el-table tr:hover > td {
  background: #f1f5ff !important;
}

.el-table .el-button[type="text"] {
  color: #6366f1;
  font-weight: 500;
  border-radius: 6px;
  transition: background 0.2s, color 0.2s;
}

.el-table .el-button[type="text"]:hover {
  background: #e0e7ff;
  color: #3b3b3b;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.upload-area {
  width: 100%;
}

.upload-area .el-upload-dragger {
  width: 100%;
  height: 200px;
}

.file-preview {
  padding: 20px;
}

.image-preview {
  text-align: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 600px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.document-preview {
  border: 1px solid #e0e7ef;
  border-radius: 8px;
  overflow: hidden;
}

.file-info-preview {
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.preview-header h3 {
  color: #2c3e50;
  margin-bottom: 16px;
}

.preview-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.preview-actions {
  display: flex;
  gap: 12px;
}

.share-content {
  padding: 20px 0;
}

.share-info h4 {
  color: #2c3e50;
  margin-bottom: 8px;
}

.share-info p {
  color: #666;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-card {
  border: none;
  transition: all 0.3s;
}

.el-card:hover {
  box-shadow: 0 4px 20px rgba(80, 120, 200, 0.12);
}

.el-tag {
  border-radius: 6px;
  font-weight: 500;
}

.el-select {
  width: 180px;
}

.el-date-picker {
  width: 320px;
}

.el-input {
  width: 180px;
}
</style>
